#include <iostream>
#include "manualwidget.h"

ManualWidget::ManualWidget( QString lang_ )
{
setupUi(this);
readSettings();

lang = QLatin1String("en");
    if ( true != lang_.isEmpty() )
    {
    lang = lang_;
    }

QStringList search_paths;
QString images_path = QCoreApplication::applicationDirPath();
images_path.append( QDir::separator() );
images_path.append( QLatin1String("ncat-manual") );
search_paths << images_path;
textBrowser->setSearchPaths(search_paths);

// Chapter 1
chapter_names[0] = tr("I Basics");
QStringList c0;
c0 << tr("1.1 Connect to DB");
c0 << tr("1.2 Select collection");
c0 << tr("1.3 View record");
c0 << tr("1.4 Sort and filter records");
c0 << tr("1.5 Add record");
c0 << tr("1.6 Edit record\'s definitions");
c0 << tr("1.7 Edit record\'s description");
c0 << tr("1.8 Add images and documents");
c0 << tr("1.9 Add references");
c0 << tr("1.10 Delete records");
c0 << tr("1.11 Copy records");
c0 << tr("1.12 Add attributes");
c0 << tr("1.13 Edit field");
paragr_names[0] = c0;
chapters[0] = c0.size();

// Chapter 2
chapter_names[1] = tr("II Record");
QStringList c1;
c1 << tr("2.1 Definitions");
c1 << tr("2.2 Decription");
c1 << tr("2.3 Images");
c1 << tr("2.4 Documents");
c1 << tr("2.5 References");
c1 << tr("2.6 Create document");
paragr_names[1] = c1;
chapters[1] = c1.size();

// Chapter 3
chapter_names[2] = tr("III Collection");
QStringList c2;
c2 << tr("3.1 Sorting");
c2 << tr("3.2 Filter");
c2 << tr("3.3 Configure collection\'s view");
c2 << tr("3.4 View collection\'s charts");
c2 << tr("3.5 View collection\'s value");
c2 << tr("3.6 Export data to MS XML spreadsheet");
c2 << tr("3.7 Import data from MS XML spreadsheet");
c2 << tr("3.8 Print records");
c2 << tr("3.9 Empty collection");
c2 << tr("3.10 Run SQL query");
c2 << tr("3.11 Import collection from N-CAT SQLite database");
c2 << tr("3.12 Export collection to SQLite database");
c2 << tr("3.13 Import collection from NUDS XML file");
c2 << tr("3.14 Export collection to NUDS XML file");
paragr_names[2] = c2;
chapters[2] = c2.size();

// Chapter 4
chapter_names[3] = tr("IV Database");
QStringList c3;
c3 << tr("4.1 Firedbird SQL Engine");
c3 << tr("4.2 Database file");
c3 << tr("4.3 Backup database");
c3 << tr("4.4 Restore database");
c3 << tr("4.5 Validate");
c3 << tr("4.5 Repair corrupted database");
c3 << tr("4.6 Work with large tables");
c3 << tr("4.7 Indexes");
c3 << tr("4.8 Install advanced tools");
c3 << tr("4.9 Create new database");
c3 << tr("4.10 Collection\'s schema");
c3 << tr("4.11 Open external database");
paragr_names[3] = c3;
chapters[3] = c3.size();

// Chapter 5
chapter_names[4] = tr("V Application");
QStringList c4;
c4 << tr("5.1 Languages and encodings");
c4 << tr("5.2 Fonts");
c4 << tr("5.3 Look");
c4 << tr("5.4 Splash image");
paragr_names[4] = c4;
chapters[4] = c4.size();

QMapIterator<int, int> chapters_i(chapters);
    while ( true == chapters_i.hasNext() )
    {
    chapters_i.next();
    QTreeWidgetItem * i0 = new QTreeWidgetItem(treeWidget);
    i0->setText( 0, chapter_names.value( chapters_i.key() ) );
    QStringList l = paragr_names.value( chapters_i.key() );
        for ( int z = 0; z < chapters_i.value(); ++z )
        {
        QTreeWidgetItem * i1 = new QTreeWidgetItem(i0);
        i1->setText( 0, l.at(z) );
        }
    }

QObject::connect( treeWidget,
                  SIGNAL( itemClicked( QTreeWidgetItem *, int ) ),
                  this,
                  SLOT( show_chapter( QTreeWidgetItem *, int ) ) );
QObject::connect( nextButton,
                  SIGNAL( clicked() ),
                  this,
                  SLOT( next_chapter() ) );
QObject::connect( backButton,
                  SIGNAL( clicked() ),
                  this,
                  SLOT( prev_chapter() ) );

}

ManualWidget::~ManualWidget()
{
}

void ManualWidget::show_chapter( QTreeWidgetItem * i, int c )
{
QString y = i->text(c);
QString chapter = y.section(" ", 0, 0);
//std::cout << chapter.toStdString() << std::endl;

    if ( true != chapter.isEmpty() )
    {
    QString s = chapter;
    s.append( QLatin1String("_") );
    s.append(lang);
    s.append( QLatin1String(".html") );

    QString path = QCoreApplication::applicationDirPath();
    path.append( QDir::separator() );
    path.append( QLatin1String("ncat-manual") );
    path.append( QDir::separator() );
    path.append(s);
    QFile file(path);
    bool ok = false;
    ok = file.open( QIODevice::ReadOnly );
        if ( ok != true )
        {
        QString m = QLatin1String("<html><body>");
        m.append( tr("Can not open") );
        m.append( QLatin1String(" ") );
        m.append( QDir::toNativeSeparators(path) );
        m.append( QLatin1String("</html></body>") );
        textBrowser->clear();
        textBrowser->setHtml(m); 
        return;
        }
    QByteArray data = file.readAll();
    file.close();
    QString text = QString::fromUtf8( data.constData() );
    textBrowser->clear();
    textBrowser->setHtml(text);
    }
}

void ManualWidget::next_chapter()
{
QItemSelectionModel * selectionModel = treeWidget->selectionModel();
    if ( NULL == selectionModel )
    {
    return;
    }
QModelIndexList currentSelection = selectionModel->selectedIndexes();
    if ( true == currentSelection.isEmpty() )
    {
    return;
    }
QModelIndex current_index = QModelIndex( currentSelection.at(0) );
    if ( true != current_index.isValid() )
    {
    return;
    }
QTreeWidgetItem * i = treeWidget->currentItem();
    if ( NULL == i)
    {
    return;
    }
QTreeWidgetItem * p = i->parent();
    if ( NULL != p )
    {
        if ( true != p->isExpanded() )
        {
        p->setExpanded(true);
        }
    }

    if ( i->childCount() > 0 )
    {
        if ( true != i->isExpanded() )
        {
        i->setExpanded(true);
        }
    }

QModelIndex next = treeWidget->indexBelow(current_index);
    if ( true == next.isValid() )
    {
    qApp->processEvents();
    selectionModel->setCurrentIndex(next, QItemSelectionModel::SelectCurrent);
    qApp->processEvents();
    QTreeWidgetItem * i_next = treeWidget->currentItem();
    show_chapter( i_next, 0 );
    }
}

void ManualWidget::prev_chapter()
{
QItemSelectionModel * selectionModel = treeWidget->selectionModel();
    if ( NULL == selectionModel )
    {
    return;
    }
QModelIndexList currentSelection = selectionModel->selectedIndexes();
    if ( true == currentSelection.isEmpty() )
    {
    return;
    }
QModelIndex current_index = QModelIndex( currentSelection.at(0) );
    if ( true != current_index.isValid() )
    {
    return;
    }
QTreeWidgetItem * i_test = treeWidget->currentItem();
    if ( NULL == i_test )
    {
    return;
    }
QTreeWidgetItem * p = i_test->parent();
    if ( NULL != p )
    {
        if ( true != p->isExpanded() )
        {
        p->setExpanded(true);
        }
    }

QModelIndex back = treeWidget->indexAbove(current_index);
    if ( true == back.isValid() )
    {
    qApp->processEvents();
    selectionModel->setCurrentIndex(back, QItemSelectionModel::SelectCurrent);
    qApp->processEvents();

    QTreeWidgetItem * i = treeWidget->currentItem();
        if ( NULL == i)
        {
        return;
        }

        if ( i->childCount() > 0 )
        {
            if ( true != i->isExpanded() )
            {
            i->setExpanded(true);
            }
        qApp->processEvents();
        selectionModel->setCurrentIndex(current_index, QItemSelectionModel::SelectCurrent);
        qApp->processEvents();

        QModelIndex back_real = treeWidget->indexAbove( current_index );
            if ( back_real.isValid() )
            {
            qApp->processEvents();
            selectionModel->setCurrentIndex(back_real, QItemSelectionModel::SelectCurrent);
            qApp->processEvents();

            QTreeWidgetItem * i_real = treeWidget->currentItem();
            show_chapter( i_real, 0 );
            }
        }
        else
        {
        show_chapter( i, 0 );
        }
    }
}

void ManualWidget::readSettings()
{
QSettings settings( QSettings::IniFormat,
                    QSettings::UserScope,
                    QApplication::organizationName(),
                    QApplication::applicationName() );
settings.setFallbacksEnabled(false);                
settings.beginGroup( QLatin1String("ManualWidget") );
resize( settings.value( QLatin1String("size"), QSize( 750, 550 ) ).toSize() );
move( settings.value( QLatin1String("pos"), QPoint( 0, 0 ) ).toPoint() );
settings.endGroup();
}

void ManualWidget::writeSettings()
{
QSettings settings( QSettings::IniFormat,
                    QSettings::UserScope,
                    QApplication::organizationName(),
                    QApplication::applicationName() );
settings.setFallbacksEnabled(false);
settings.beginGroup( QLatin1String("ManualWidget") );
settings.setValue( QLatin1String("size"), QVariant( this->size() ) );
settings.setValue( QLatin1String("pos"), QVariant( this->pos() ) );
settings.endGroup();
}

void ManualWidget::closeEvent(QCloseEvent * e)
{
writeSettings();
e->accept();
}
